package com.market.cash.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.market.cash.R
import com.market.cash.databinding.CashFeedbackBinding
import com.market.cash.databinding.CashFeedbackQuestionTypeItemBinding
import com.market.cash.http.ApiService
import com.market.cash.http.ApiService.addCommonParams
import com.market.cash.pro.ProActivity
import com.market.cash.ui.adapter.CashRootFeedbackImageAdapter
import com.market.cash.ui.presenter.CashRootFeedbackPresenter
import com.market.cash.ui.presenter.CashRootUploadPresenter
import com.market.cash.ui.view.ICashRootFeedbackView
import com.market.cash.ui.view.ICashRootUploadView
import com.market.cash.utils.adapter.CashRootOnItemChildClickListener
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import com.market.cash.utils.imgcovert.ImageConvert
import com.market.cash.utils.log.CashRootLog
import org.json.JSONObject
import java.io.File


/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/28 13:45
 * @Annotation：意见反馈
 */
class FeedbackActivity: ProActivity(), ICashRootFeedbackView, ICashRootUploadView {
    lateinit var binding: CashFeedbackBinding
    private var presenter: CashRootFeedbackPresenter? = null
    private var upLoadPresenter: CashRootUploadPresenter? = null

    //图片列表
    private var imgAdapter: CashRootFeedbackImageAdapter? = null

    //图片压缩后存储的临时文件
    private var destinationDirectory: File? = null
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    companion object {
        private const val INTENT_KEY_STAR_COUNT = "starCount"
        fun start(context: Context, count: String? = "") {
            val intent = Intent(context, FeedbackActivity::class.java)
            intent.putExtra(INTENT_KEY_STAR_COUNT, count)
            context.startActivity(intent)
        }
    }

    override fun getCashRootRootView(): View {
        binding = CashFeedbackBinding.inflate(layoutInflater)
        return binding.root
    }

    @SuppressLint("SetTextI18n")
    override fun initCashRootView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#FFFFFF"))
        setCashRootTitleBarVisibility(View.VISIBLE)
        setCashRootTextTitle(getString(R.string.feedback_title))
        setCashRootTextTitleGravity(Gravity.CENTER)
        setCashRootBackBtnRes(R.mipmap.cash_back_black)
        setCashRootRightBtnRes(R.mipmap.cash_kefu_black)

        initCashRootRecyclerView()

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                CashRootLog.e("uri.path>>>>>>>>>>>>>>${uri.path}")
                ImageConvert.covert(context = this, uri = uri) { localPath, bitmap ->
                    CashRootLog.e(">>>>>>>>>>>>>localPath: $localPath")
                    if (localPath != null){
                        //最多只能选三张
                        if (imgAdapter!!.itemCount == 3){
                            imgAdapter!!.removeItem(0)
                        }
                        val imgObj = JSONObject()
                        imgObj.put("isDefault",false)
                        imgObj.put("imgPath",localPath)
                        imgAdapter!!.addLastItem(imgObj)

                        showCashRootLoading()
                        if (upLoadPresenter == null){
                            upLoadPresenter = CashRootUploadPresenter(this)
                        }
                        upLoadPresenter!!.onCashRootUploadImageAction(localPath)
                    }
                }

            } else {
                CashRootLog.e("No media selected")
            }
        }
    }

    override fun initCashRootListener() {
        //联系客服
        rootViewBinding.imgKefu.setOnClickListener {
            KefuActivity.start(this,"Feedback Page")
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_CUSTOMER,"Feedback Page")
        }
        //输入框监听
        binding.editRemark.addTextChangedListener(IRemarkChangeListener)
        binding.editRemark.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus && binding.editRemark.text.toString().isNotEmpty()){
                addCashRootEventPoint(CashRootEventType.FORM.CASHROOT_FORM_USER_FEEDBACK_DESCRIBE,binding.editRemark.text.toString())
            }
        }

        //提交
        binding.btnSubmit.setOnClickListener {
            //问题类型
            if (getSelectTypeItem() == null){
                showCashRootToast(getString(R.string.feedback_please_select_question_type))
                return@setOnClickListener
            }
            val remark = binding.editRemark.text.toString()
            if (remark.isEmpty()){
                showCashRootToast(getString(R.string.feedback_remark_title))
                return@setOnClickListener
            }
            showCashRootLoading(isTOuchOut = false, isCancel = true)
            val params = JSONObject().addCommonParams().apply {
                put("path", ApiService.API_PATH.CASHROOT_API_FEEDBACK_SUBMIT_PATH)
                put("type",getSelectTypeItem()!!.optString("value"))//反馈类型
                put("opinion",remark)//反馈内容
            }
            val imgUrls = getSelectImageUrls()
            if (imgUrls.isNotEmpty()){
                params.put("images",imgUrls)
            }
            val starCount = getStarCount()
            if (starCount.isNotEmpty()){
                params.put("starNum",starCount)//从评价弹窗进入反馈页,需要传星级数量
            }

            presenter!!.submitCashRootFeedbackAction(params)
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_USER_FEEDBACK_SUBMIT)
        }
    }

    override fun initCashRootData() {
        if (presenter == null){
            presenter = CashRootFeedbackPresenter(this)
        }
        presenter!!.loadQuestionTypeListAction()

        val imgObj = JSONObject()
        imgObj.put("isDefault",true)
        imgAdapter!!.addFirstItem(imgObj)

        //牌照信息
        if (!CashRootCustomConfigsHelper.isCashRootShowLicense()){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(initCashRootLicenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 初始化图片列表
     */
    private fun initCashRootRecyclerView() {
        binding.recyclerView.setHasFixedSize(false)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.recyclerView.layoutManager = layoutManager
        imgAdapter = CashRootFeedbackImageAdapter(binding.recyclerView)
        binding.recyclerView.adapter = imgAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        imgAdapter!!.setOnItemChildClickListener(CashRootOnItemChildClickListener { parent, childView, position ->
            val item = imgAdapter!!.getItem(position)
            when (childView.id) {
                R.id.imgRemove -> {//删除
                    if (!item.optBoolean("isDefault")) {
                        imgAdapter!!.removeItem(position)

                        //是否需要添加默认图片
                        var isAddDefault = true
                        for (i in 0..<imgAdapter!!.itemCount) {
                            if (imgAdapter!!.getItem(i).optBoolean("isDefault")) {
                                isAddDefault = false
                                break
                            }
                        }
                        if (isAddDefault) {
                            val imgObj = JSONObject()
                            imgObj.put("isDefault", true)
                            imgAdapter!!.addFirstItem(imgObj)
                        }
                    }
                }

                R.id.addLayout -> {//选择图片
                    if (item.optBoolean("isDefault")) {
                        hasRequestPermissions()
                    }
                }
            }
        })
    }

    private val IRemarkChangeListener = object: TextWatcher{
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
            val textLength = s!!.length
        }
    }

    /**
     * 设置问题类型列表
     */
    private fun setQuestionTypeList(){
        binding.flexboxLayout.removeAllViews()
        val typeList = presenter!!.getTypeList()
        for (i in 0..< typeList.size) {
            val item = typeList[i]
            val itemBinding = CashFeedbackQuestionTypeItemBinding.inflate(layoutInflater)
            itemBinding.textValue.text = getString(item.optInt("title"))
            if (item.optBoolean("isSelect")){
                itemBinding.textValue.setTextColor(Color.parseColor("#435CFA"))
                itemBinding.textValue.setBackgroundResource(R.drawable.cash_circle_frame_435cfa)
            } else {
                itemBinding.textValue.setTextColor(Color.parseColor("#8C8EAF"))
                itemBinding.textValue.setBackgroundResource(R.drawable.cash_circle_frame_dfe1e8)
            }
            binding.flexboxLayout.addView(itemBinding.root)
            itemBinding.textValue.setOnClickListener {
                if (item.optBoolean("isSelect")){
//                    item.put("isSelect",false)
//                    setQuestionTypeList()
                    return@setOnClickListener
                }
                for (index in 0..< typeList.size){
                    val obj = typeList[index]
                    if (index == i){
                        obj.put("isSelect",true)
                        addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_USER_FEEDBACK_QUESTION_TYPE,getString(obj.optInt("title")))
                    } else {
                        obj.put("isSelect",false)
                    }
                }
                setQuestionTypeList()
            }
        }
    }

    /**
     * 获取选择的问题类型
     */
    private fun getSelectTypeItem(): JSONObject?{
        var selectItem: JSONObject? = null
        for (i in 0..<presenter!!.getTypeList().size){
            val obj = presenter!!.getTypeList()[i]
            if (obj.optBoolean("isSelect")){
                selectItem = obj
                break
            }
        }
        return selectItem
    }

    /**
     * 获取上传的图片链接
     */
    private fun getSelectImageUrls(): String{
        var imgUrls = ""
        for (i in 0..<imgAdapter!!.itemCount){
            val item = imgAdapter!!.getItem(i)
            if (item.optBoolean("isDefault")){
                continue
            }
            imgUrls = imgUrls + item.optString("imgUrl") + ","
        }
        if (imgUrls.isNotEmpty()){
            imgUrls = imgUrls.substring(0,imgUrls.length - 1)
        }
        return imgUrls
    }

    /**
     * 获取评分数量
     */
    private fun getStarCount(): String {
        if (intent.extras == null){
            return ""
        }
        return if (intent.extras!!.getString(INTENT_KEY_STAR_COUNT) == null) "" else intent.extras!!.getString(INTENT_KEY_STAR_COUNT).toString()
    }

    /**
     * 设置意见反馈问题类型列表
     */
    override fun setCashRootQuestionTypeList(typeList: ArrayList<JSONObject>) {
        setQuestionTypeList()
    }


    /**
     * 图片上传成功，需要删除临时文件
     */
    override fun showCashRootUploadImageSuccess(imgPath: String, imgUrl: String) {
        addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_USER_FEEDBACK_UPLOAD_IMAGE,imgUrl)
        val lastItem = imgAdapter!!.lastItem as JSONObject
        lastItem.put("imgUrl",imgUrl)

        if (destinationDirectory != null && destinationDirectory!!.isFile){
            destinationDirectory!!.delete()
        }
    }

    /**
     * 显示反馈提交成功
     */
    override fun showCashRootSubmitSuccess() {
        Handler(Looper.getMainLooper()).postDelayed({
            finish()
        },1000)
    }


    /**
     * 申请权限
     */
    private fun hasRequestPermissions(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    override fun onStart() {
        super.onStart()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_USER_FEEDBACK_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_USER_FEEDBACK_END)
    }
}